/**
 * 用于面试中自定义 audio 需求
 * 视需求情况自行扩展
 */

import React from 'react';
import { Menu, Dropdown, Tooltip } from 'antd';
import styles from './index.less';

const rates = ['1.0', '1.2', '1.5', '2.0', '3.0'];

export default function WebAudio({ ...rest }) {
    const [playbackRate, setPlaybackRate] = React.useState('1.0');
    const audioRef = React.useRef();

    const handleChange = ({ key }) => {
        setPlaybackRate(key);
    };

    React.useEffect(() => {
        if (audioRef.current) {
            audioRef.current.playbackRate = playbackRate;
        }
    }, [playbackRate]);

    const menu = (
        <Menu onClick={handleChange}>
            {rates.map(item => (
                <Menu.Item key={item}>{`${item}x`}</Menu.Item>
            ))}
        </Menu>
    );

    /**
     * 同步浏览器自带audio控件改变播放速度
     */
    const onRateChange = () => {
        handleChange({ key: audioRef.current.playbackRate });
    };

    return (
        <div className={styles.wrap}>
            <audio {...rest} ref={audioRef} preload="metadata" onRateChange={onRateChange}>
                <track kind="captions" />
            </audio>
            <Dropdown placement="bottomCenter" overlay={menu} getPopupContainer={trigger => trigger.parentNode}>
                <Tooltip title="切换倍速" getPopupContainer={trigger => trigger.parentNode}>
                    <span className={styles.highLight}>
                        {Number(playbackRate) === 1 ? (
                            <span style={{ marginLeft: 8 }}>倍速</span>
                        ) : (
                            <span style={{ marginLeft: 8 }}>{`${playbackRate}x`}</span>
                        )}
                    </span>
                </Tooltip>
            </Dropdown>
        </div>
    );
}
